import { asyncRoutes, constantRoutes } from '@/router'
import { checkPermission, CheckAccountType } from '@/utils/permission'
/**
 * Use meta.role to determine if the current user has permission
 * @param menus
 * @param route
 */
function hasPermission(menus, route) {
    if (route.meta && route.meta.permission) {
        return checkPermission(route.meta.permission, menus)
    } else {
        return true
    }
}

function CheckAccountTypePerimisson(login_user_account_type, route) {
    if (route.meta && route.meta.accounttype) {
        return CheckAccountType(route.meta.accounttype, login_user_account_type)
    } else {
        return true
    }
}


/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param menus
 */
export function filterAsyncRoutes(routes1, menus, account_type) {
    const res = []

    routes1.forEach(route => {
        const tmp = {...route }
        if (CheckAccountTypePerimisson(account_type, tmp) && hasPermission(menus, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, menus, account_type)
            }
            res.push(tmp)
        }
    })

    return res
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    }
}

const actions = {
    generateRoutes({ commit }, menus, account_type) {
        return new Promise(resolve => {
            let accessedRoutes
            accessedRoutes = filterAsyncRoutes(asyncRoutes, menus, account_type)
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}